package edu.ptu.shortlink.project.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import edu.ptu.shortlink.project.dao.entity.LinkLocaleStatsDO;
import edu.ptu.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO;
import edu.ptu.shortlink.project.dto.req.ShortLinkStatsReqDTO;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.project.dao.mapper
 * @Author: HYJ
 * @CreateTime: 2025-05-07  05:17
 * @Description: 地区统计Mapper
 * @Version: 1.0
 */
public interface LinkLocaleStatsMapper extends BaseMapper<LinkLocaleStatsDO> {

    @Insert("INSERT INTO t_link_locale_stats ( full_short_url, gid, date, cnt, city, province, country, adcode, create_time, update_time, del_flag ) "
            + "VALUES (#{linkLocaleStats.fullShortUrl},#{linkLocaleStats.gid},#{linkLocaleStats.date}, #{linkLocaleStats.cnt}, #{linkLocaleStats.city}, #{linkLocaleStats.province}, #{linkLocaleStats.country},#{linkLocaleStats.adcode}, NOW(), NOW(), 0 ) "
            + "ON DUPLICATE KEY UPDATE cnt = cnt + #{linkLocaleStats.cnt}; ")
    void shortLinkLocaleStatsInc(@Param("linkLocaleStats") LinkLocaleStatsDO linkLocaleStats);

    @Select("SELECT " +
            "    tlls.province, " +
            "    SUM(tlls.cnt) AS cnt " +
            "FROM " +
            "    t_link tl INNER JOIN " +
            "    t_link_locale_stats tlls ON tl.full_short_url = tlls.full_short_url " +
            "WHERE " +
            "    tlls.full_short_url = #{param.fullShortUrl} " +
            "    AND tl.gid = #{param.gid} " +
            "    AND tl.del_flag = '0' " +
            "    AND tl.enable_status = #{param.enableStatus} " +
            "    AND tlls.date BETWEEN #{param.startDate} and #{param.endDate} " +
            "GROUP BY " +
            "    tlls.full_short_url, tl.gid, tlls.province;")
    List<LinkLocaleStatsDO> listLocaleByShortLink(@Param("param") ShortLinkStatsReqDTO requestParam);

    /**
     * 根据分组获取指定日期内地区统计数据
     */
    @Select("SELECT " +
            "    tlls.province, " +
            "    SUM(tlls.cnt) AS cnt " +
            "FROM " +
            "    t_link tl INNER JOIN " +
            "    t_link_locale_stats tlls ON tl.full_short_url = tlls.full_short_url " +
            "WHERE " +
            "    tlls.gid = #{params.gid} " +
            "    AND tlls.date BETWEEN #{params.startDate} and #{params.endDate} " +
            "    AND tl.del_flag = '0' " +
            "    AND tl.enable_status = '0' " +
            "GROUP BY " +
            "    tlls.gid, tlls.province;")
    List<LinkLocaleStatsDO> listLocaleByGroup(@Param("params") ShortLinkGroupStatsReqDTO requestParam);
}
